import {connect} from "dva";
import {Button, Form, Input, message, Modal, Radio, Spin, Table} from "antd";
import React, {useEffect, useState} from "react";
import {getShopId} from "@/utils/localStorage";

const ModalList = connect(({ coupons, loading }) => ({
  ...coupons,
  loading: loading.models.coupons,
}))(Form.create()(props => {
  const [KeysId, setKeysId] = useState("")
  const [InputChangs, setInputChangs] = useState("")
  useEffect(() => {
    props.dispatch({
      type: 'coupons/list',
      payload: {
        pageNumber: 1,
        pageSize: 10,
        sourceShopId: getShopId()
      },
    });
  }, [])
  const onSelectChange = (selectedRowKeys, is) => {
    let Id = []
    for (let i = 0; i < is.length; i++) {
      Id.push(is[i].id)
    }
    setKeysId(Id.toString())
  };
  const InputChang = (e) => {
    setInputChangs(e.target.value)
  }
  const onSsTable = () => {
    props.dispatch({
      type: 'coupons/list',
      payload: {
        title: InputChangs,
        pageNumber: 1,
        pageSize: 100,
        sourceShopId: getShopId()
      },
    })
  }
  const onThepage = (e) => {
    props.dispatch({
      type: 'coupons/list',
      payload: {
        title: InputChangs,
        pageNumber: e.current,
        pageSize: 100,
        sourceShopId: getShopId()
      },
    })
  }
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };
  const { getFieldDecorator, validateFields } = props.form;
  const RadioGroup = Radio.Group;
  const columns = [
    {
      title: '优惠券名称',
      dataIndex: 'title',
    },
    {
      title: '发放总量',
      dataIndex: 'num',
    },
    {
      title: '库存',
      dataIndex: 'leftNum',
    },
    {
      title: '面额',
      dataIndex: 'discountAmount',
    },
    {
      title: '使用条件',
      dataIndex: 'minAmount',
      render: text => (text === 0 ? `不限制` : `满${text}元使用`),
    },
    {
      title: '每人限领',
      dataIndex: 'userLimitNum',
      render: text => (text === '0' ? '不限' : `${text}张`),
    },
    {
      title: '时间设置',
      dataIndex: 'type',
      render: (text, record) =>
        record.delayDayNum ? (
          `自领取${record.delayDayNum}天内使用`
        ) : (
          <div>
            <div>开始：{record.startTime}</div>
            <div>结束：{record.endTime}</div>
          </div>
        ),
    },
  ];
  const okHandle = e => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        if (props.control) {
          props.dispatch({
            type: 'coupons/getupdate',
            payload: {
              id: props.Data.id,
              name: values.name,
              status: values.status,
            },
            callback: (res) => {
              if (res.msg === "操作成功") {
                message.success('修改大礼包成功')
                props.onCancel()
              }
              props.couponPackageList()
            }
          })
        } else {
          if (KeysId === "") {
            message.error('请选择优惠券～')
          } else {
            props.dispatch({
              type: 'coupons/couponPackage',
              payload: {
                ...values,
                sourceShopId: getShopId(),
                templateIds: KeysId
              },
              callback: (res) => {
                if (res.msg === "操作成功") {
                  message.success('新增大礼包成功')
                  props.onCancel()
                }
                props.couponPackageList()
              }
            })
          }
        }
        
      }
    });
  };
  
  return (
    <Modal
      title={props.titls}
      visible={props.visible}
      onCancel={props.onCancel}
      style={{ minWidth: 1025 }}
      destroyOnClose={true}
      onOk={okHandle}
    >
      <Spin spinning={false}>
        <Form {...formItemLayout} layout="horizontal" className="package-modal">
          <Form.Item label="大礼包名称" required>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入大礼包名称' }],
              initialValue: props.Data.name
            })(
              <Input placeholder="请输入大礼包名称" />
            )}
          </Form.Item>
          <Form.Item label="新用户专享" required>
            {getFieldDecorator('forNew', {
              rules: [{ required: true, message: '请选择' }],
              
              initialValue: props.Data.forNew || "T"
            })(
              <RadioGroup disabled={props.control}>
                <Radio value="T">是</Radio>
                <Radio value="F">否</Radio>
              </RadioGroup>
            )}
          </Form.Item>
          <Form.Item label="大礼包状态" required>
            {getFieldDecorator('status', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: props.Data.status || "VALID"
            })(
              <RadioGroup>
                <Radio value="VALID">有效</Radio>
                <Radio value="INVALID">失效</Radio>
              </RadioGroup>
            )}
          </Form.Item>
          {
            !props.control ? <Form.Item label="优惠券名称" >
              <div style={{
                display: 'flex',
              }}>
                <Input placeholder="请输入优惠券名称" style={{ width: 200, marginRight: 30 }} onChange={InputChang} />
                <Button onClick={onSsTable} type="primary">搜索</Button>
              </div>
            </Form.Item> : null
          }
        </Form>
        <Table columns={columns}
               dataSource={props.control ? props.Data.couponList : props.listData}
               size="middle"
               pagination={{
                 current: 1,
                 pageSize: 10,
               }}
               onChange={onThepage}
               rowSelection={props.control ? null : {
                 onChange: onSelectChange,
               }}
        />
      </Spin>
    </Modal>
  )
}))

export default ModalList
